<?php


class ObservationdepthattributeTable extends Doctrine_Table
{
    
    public static function getInstance()
    {
        return Doctrine_Core::getTable('Observationdepthattribute');
    }

    public function getAttributeListQuery($dql, $params = array())
    {
        $q =    Doctrine_Query::create()
                ->select('a.attributename, oda.attributevalue, u.unit, oda.id')
                ->from('observationdepthattribute oda')
                ->leftJoin('oda.Attribute a')
                ->leftJoin('oda.Unit u')
                ->where($dql, $params)
                ->orderBy('a.attributename');

        // wierd absurd workaround
        $result  = $q->fetchArray();
//
//        sfContext::getInstance()->getLogger()->debug('attribute list: '. count($result));

        return $q;
    }

    /**
     * Insert or update collection of records into database
     * @param array $collection array of record
     * @return boolean if success return true, otherwise false
     */
    public function bulkInsertUpdate($collection)
    {
        if (!$collection)
            return false;

        $records = new Doctrine_Collection($this->getTableName());

        //
        $depthId;

        foreach($collection as $line)
        {

            if (is_null($line) || $line == "")
                continue;

            $record;

            // if id exists then it is editing, otherwise new attribute
            $record = $this->findOrNew(isset($line['id']) ? $line['id'] : "");

            // if depthid doesnt exist then it is new depth
            if (empty($line['depthid']))
            {
                if (empty($depthId))
                {
                    // create new observation depth record
                    $obsDepth = Doctrine::getTable('Observationdepth')
                                ->create(array(
                                            'observationid'             => $line['obsid'],
                                            'observationdepth'          => $line['depth'])
                                        );
                    $obsDepth->save();
                    $depthId = $obsDepth->id;
                }

                $line['depthid'] = $depthId;
            }

            $record->observationdepthid = $line['depthid'];
            $attribute = Doctrine::getTable('Attribute')->findOrCreate(array(
                'attributename'     => $line['attributename'],
                'unit'              => $line['unit']
                ));
            $record->attributeid = $attribute->id;
            $record->attributevalue = $line['attributevalue'];
            $unit = Doctrine::getTable('Unit')->findOrCreate(array('unit' => $line['unit']));
            $record->unitid = $unit->id;

            $records->add($record);
        }

        try
        {
            $records->save();

            ObjectunitTable::getInstance()->bulkInsertUpdate($records, Types::$OBJECT_TYPE_ATTRIBUTE);

            return true;
        } 
        catch (Exception $e)
        {
            if (sfConfig::get('sf_logging_enabled'))
            {
              sfContext::getInstance()->getLogger()->debug($e->getMessage());
            }
            return false;
        }
    }

    /**
     * Find a record by $id, or if not found return new object
     * @param int $id
     * @return Observationdepthattribute
     */
    public function findOrNew($id)
    {
        if (!empty($id))
        {
            return $this->find(array($id));
        }
        else
        {
            $record = new Observationdepthattribute($this->getTableName(), true);
            return $record;
        }
    }

    /**
     * delete observation-depth-attribute records
     * @param array $keys array of ids
     * @return boolean
     */
    public function delete($keys) {
        try {
            $to_remove_records = $this->findByDql('id IN (?' . str_repeat(',?', count($keys)-1) . ')', $keys);
            $to_remove_records->delete();
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
}